import '@/styles/global.css'
import 'dayjs/locale/ar'
import 'dayjs/locale/en'
import '@/assets/animate.min.css'

import { App as AppProvider, ConfigProvider, Empty } from 'antd'
import arEG from 'antd/locale/ar_EG'
import enUS from 'antd/locale/en_US'
import dayjs from 'dayjs'
import type { NextPage } from 'next'
import type { AppProps } from 'next/app'
import Head from 'next/head'
import { useRouter } from 'next/router'
import cookies from 'next-cookies'
import NProgress from 'nprogress'
import { ReactElement, ReactNode, useEffect } from 'react'
import { Provider } from 'react-redux'
import { ParallaxProvider } from 'react-scroll-parallax'

import EmptySvg from '@/assets/svg/empty.svg'
import { GlobalContext } from '@/context'
import store from '@/store'
import changeTheme from '@/utils/changeTheme'
import useStorage from '@/utils/useStorage'

type NextPageWithLayout = NextPage & {
  // eslint-disable-next-line no-unused-vars
  getLayout?: (page: ReactElement) => ReactNode
}
interface RenderConfig {
  arcoLang: string
  arcoTheme: string
}
type AppPropsWithLayout = AppProps & {
  Component: NextPageWithLayout
}
NProgress.settings.showSpinner = false
export default function MyApp({
  Component,
  pageProps,
  renderConfig,
}: AppPropsWithLayout & { renderConfig: RenderConfig }) {
  const { arcoLang, arcoTheme } = renderConfig || {}
  const [lang, setLang] = useStorage('arco-lang', arcoLang || 'ar-EG')
  const [theme, setTheme] = useStorage('arco-theme', arcoTheme || 'light')

  useEffect(() => {
    dayjs.locale(lang === 'en-US' ? 'en' : 'ar')
  }, [lang])

  const router = useRouter()

  useEffect(() => {
    const handleStart = () => {
      NProgress.set(0.4)

      NProgress.start()
    }

    const handleStop = () => {
      NProgress.done()
    }

    router.events.on('routeChangeStart', handleStart)
    router.events.on('routeChangeComplete', handleStop)
    router.events.on('routeChangeError', handleStop)

    return () => {
      router.events.off('routeChangeStart', handleStart)
      router.events.off('routeChangeComplete', handleStop)
      router.events.off('routeChangeError', handleStop)
    }
  }, [router])

  useEffect(() => {
    document.cookie = `arco-lang=${lang}; path=/`
    document.cookie = `arco-theme=${theme}; path=/`
    changeTheme(theme)
  }, [lang, theme])

  const contextValue = {
    lang,
    setLang,
    theme,
    setTheme,
  }

  // Use the layout defined at the page level, if available
  const getLayout = Component.getLayout ?? ((page) => page)
  const renderEmpty = (componentName: string | undefined): JSX.Element | undefined => {
    switch (componentName) {
      case 'Table':
        return <Empty image={<EmptySvg className={' w-48'} />} />
    }
  }

  return (
    <ParallaxProvider>
      <ConfigProvider
        locale={lang === 'en-US' ? enUS : arEG}
        direction={lang === 'en-US' ? 'ltr' : 'rtl'}
        theme={{ token: { colorPrimary: '#44C5E4' } }}
        renderEmpty={renderEmpty}
      >
        <AppProvider>
          <Provider store={store}>
            <GlobalContext.Provider value={contextValue}>
              <Head>
                <meta
                  id="viewport"
                  name="viewport"
                  content="width=device-width, initial-scale=1.0, user-scalable=no, viewport-fit=cover"
                />
                <meta
                  name="format-detection"
                  content="telephone=no, date=no, email=no, address=no"
                />
              </Head>
              {getLayout(<Component {...pageProps} suppressHydrationWarning />)}
            </GlobalContext.Provider>
          </Provider>
        </AppProvider>
      </ConfigProvider>
    </ParallaxProvider>
  )
}
/** 指标参数*/
// export function reportWebVitals(metric: NextWebVitalsMetric) {
//   console.log(metric)
// }

// fix: next build ssr can't attach the localstorage
MyApp.getInitialProps = async (appContext: { ctx: any }) => {
  const { ctx } = appContext
  const serverCookies = cookies(ctx)

  return {
    renderConfig: {
      arcoLang: serverCookies['arco-lang'] as string,
      arcoTheme: serverCookies['arco-theme'] as string,
    },
  }
}
